﻿using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UMLSynthesizer.CSharpAnalyzer.Elements;
using UMLSynthesizer.LangAnalyzer;
using UMLSynthesizer.LangAnalyzer.Elements;

namespace UMLSynthesizer.CSharpAnalyzer
{
    public class CSharpLanguageAnalyzer : LanguageAnalyzer
    {
        public override IProjectElement GetProject(IEnumerable<string> sourceFiles,
            IEnumerable<string> additionalAssemblyReferences = null)
        {
            if (sourceFiles == null || sourceFiles.Count() == 0)
                throw new ArgumentNullException("Argument can't be null or empty");

            //parse source files
            List<SyntaxTree> syntaxTrees = new List<SyntaxTree>();
            foreach (var source in sourceFiles)
                syntaxTrees.Add(CSharpSyntaxTree.ParseFile(source));

            //create compilation
            IEnumerable<string> assemblyReferences = new string[] { typeof(object).Assembly.Location };
            if (additionalAssemblyReferences != null)
                assemblyReferences = assemblyReferences.Union(additionalAssemblyReferences);

            var compilation = CSharpCompilation.Create("assemblyName");
            if (additionalAssemblyReferences != null)
                foreach (var assembly in assemblyReferences)
                    compilation = compilation.AddReferences(new MetadataFileReference(assembly));
            foreach (var tree in syntaxTrees)
                compilation = compilation.AddSyntaxTrees(tree);

            //return the project
            return new CSharpProjectElement(compilation);
        }
    }
}
